package mmc.resource.models.collada;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.ArrayList;

import java.util.List;

import mmc.Constants;
import mmc.EngineObject;
import mmc.resource.Model;

import static org.lwjgl.opengl.GL11.*;
import org.collada.x2005.x11.colladaSchema.COLLADADocument;
import org.collada.x2005.x11.colladaSchema.NodeDocument.Node;
import org.collada.x2005.x11.colladaSchema.VisualSceneDocument.VisualScene;

public class ColladaScene extends Model{
	private static FloatBuffer COLLADA_WORLD_TRANSFORM; 
	static{
		if(!Constants.IS_SERVER){
			ByteBuffer bb = ByteBuffer.allocateDirect(4*4*4);
			bb.order(ByteOrder.nativeOrder());
			COLLADA_WORLD_TRANSFORM = bb.asFloatBuffer();
			FloatBuffer cwt = COLLADA_WORLD_TRANSFORM;
			
			cwt.put(1);cwt.put(0);cwt.put(0);cwt.put(0);
			cwt.put(0);cwt.put(0);cwt.put(1);cwt.put(0);
			cwt.put(0);cwt.put(1);cwt.put(0);cwt.put(0);
			cwt.put(0);cwt.put(0);cwt.put(0);cwt.put(1);
			
			cwt.flip();
		}
	}
	
	List<ColladaNode> nodes = new ArrayList<ColladaNode>();
	
	public ColladaScene(String fileUrl){
		try {
			COLLADADocument doc = COLLADADocument.Factory.parse(ClassLoader.getSystemResourceAsStream(fileUrl));
			VisualScene v = loadScene(doc);
			for(Node n : v.getNodeArray())
				nodes.add(ColladaNode.loadNode(doc, n));
			
		} catch (Exception e) {
			throw new RuntimeException("Exception while loading Collada-File: "+e.getMessage(),e);
		}
	}
	
	public void render(EngineObject observer) {
		glPushMatrix();
		glMultMatrix(COLLADA_WORLD_TRANSFORM); //switch left-handed to right-handed coordinate system (opengl vs. collada)
		
		for(ColladaNode n : nodes){
			n.render(observer);
		}
		
		glPopMatrix();
	}
	
	private static VisualScene loadScene(COLLADADocument doc) {
		if(doc.getCOLLADA().getLibraryVisualScenesArray().length!=1 || doc.getCOLLADA().getLibraryVisualScenesArray()[0].getVisualSceneArray().length!=1)
			throw new RuntimeException("Collada-Base contains more than one scene (loading ambigious)");
		return doc.getCOLLADA().getLibraryVisualScenesArray()[0].getVisualSceneArray()[0];
		/*
		LibraryVisualScenes[] scenes = doc.getCOLLADA().getLibraryVisualScenesArray();
		
		for(LibraryVisualScenes s : scenes)
			for(VisualScene ss : s.getVisualSceneArray())
				if(ss.getName().equals(sceneName)){
					return ss;
				}
		
		ArrayList<String> sceneNames = new ArrayList<String>();
		for(LibraryVisualScenes s : scenes)
			for(VisualScene ss : s.getVisualSceneArray())
				sceneNames.add(ss.getName());
		throw new RuntimeException("Invalid scene name \""+sceneName+"\" - valid names would be: "+sceneNames);
		*/
	}
}
